package com.saoft.jcms.util;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;


/**
 * 分类显示辅助工具对象
 * @author 一克金代码
 * @date
 */
public class PageUtil {

    private static String getParameter(Page page){
        if (page.getTotal() > 0){
            HttpServletRequest request = HttpServletUtil.getRequest();
            // 获取分页参数地址
            String servletPath = request.getServletPath();
            StringBuffer param = new StringBuffer(servletPath + "?");
            Enumeration em = request.getParameterNames();
            while (em.hasMoreElements()) {
                String name = (String) em.nextElement();
                if(!"page".equals(name)){
                    String value = request.getParameter(name);
                    param.append(name + "=" + value + "&");
                }
            }
            return param.toString();
        }
        return "";
    }

    public static List<String> pageCode(Page page){
        long number = page.getCurrent();
        long totalPages = page.getPages();
        long start = 0;
        long length = 7;
        long half = length % 2 == 0 ? length / 2 : length / 2 + 1;
        List<String> codeList = new ArrayList<>();

        if(totalPages > length && number > half){
            start = number - half;
        }
        if(totalPages > length && number > totalPages - half){
            start = totalPages - length;
        }
        for (int i=1; i <= (totalPages > length ? length : totalPages); i++){
            codeList.add(String.valueOf( i + start));
        }
        if(totalPages > length && number > half){
            codeList.set(0, "1");
            codeList.set(1, "…");
        }
        if(totalPages > length && number < totalPages - (half-1)){
            codeList.set((int) (length-2), "…");
            codeList.set((int) (length-1), String.valueOf(totalPages));
        }
        return codeList;
    }

    public static String pageActive(Page page, String pageCode, String className){
        long number = page.getCurrent()-1;
        if(!"…".equals(pageCode)){
            if(number == Integer.valueOf(pageCode) - 1){
                return " "+className;
            }
        }
        return "";
    }

    public static boolean isPrevious(Page page){
        return page.hasPrevious();
    }

    public static boolean isNext(Page page){
        return page.hasNext();
    }

    public static boolean isCode(String pageCode){
        return "…".equals(pageCode);
    }

    public static String pageHref(Page page, String pageCode) {
        String paramHref = getParameter(page);
        return paramHref + "page=" + pageCode;
    }
}
